"use client";
import { useRef, useState } from 'react';
import { MapService } from '../service/MapService';
import {
  startDrawMode,
  stopDrawMode,
  enableSelectMode,
  disableSelectMode
} from '../drawing/mapDrawingActions';

interface ControlPanelProps {
  mapService: React.RefObject<MapService | null>;
}

const buttonStyle = {
  padding: '8px 10px',
  border: 'none',
  borderRadius: 8,
  backgroundColor: '#888',
  color: 'white',
  cursor: 'pointer',
  transition: 'background-color 0.2s',
  flex: 1,
  boxShadow: '0 1px 4px rgba(0,0,0,0.08)',
  outline: 'none',
  minWidth: 80,
  minHeight: 30,
};

export const ControlPanel = ({ mapService }: ControlPanelProps) => {
  const [activeDraw, setActiveDraw] = useState<string | null>(null);
  const [selectMode, setSelectMode] = useState<'single' | 'rectangle' | 'polygon'>('single');
  const [selectDropdown, setSelectDropdown] = useState(false);
  // 新增：是否正在绘图
  const [isDrawing, setIsDrawing] = useState(false);

  const handleDrawClick = (mode: 'marker' | 'polyline' | 'polygon') => {
    console.log('[DEBUG] handleDrawClick called, mode:', mode);
    setActiveDraw(mode);
    setIsDrawing(true);
    const map = mapService.current?.getMap();
    console.log('[DEBUG] map in handleDrawClick:', map);
    if (map) {
      const drawInteraction = mapService.current!.getDrawInteraction();
      console.log('[DEBUG] drawInteraction in handleDrawClick:', drawInteraction);
      startDrawMode(
        map,
        { current: drawInteraction },
        { current: mapService.current!.getSelectInteraction() },
        mode,
        mapService.current!.addMarker?.bind(mapService.current),
        mapService.current!.drawLine?.bind(mapService.current),
        mapService.current!.drawPolygon?.bind(mapService.current)
      );
    }
  };

  // 新增：停止绘制
  const handleStopDraw = () => {
    console.log('[DEBUG] handleStopDraw called');
    setIsDrawing(false);
    setActiveDraw(null);
    const map = mapService.current?.getMap();
    console.log('[DEBUG] map in handleStopDraw:', map);
    if (map) {
      const drawInteraction = mapService.current!.getDrawInteraction();
      console.log('[DEBUG] drawInteraction in handleStopDraw:', drawInteraction);
      stopDrawMode(
        { current: drawInteraction },
        { current: mapService.current!.getSelectInteraction() },
        (onSelect, mode) => enableSelectMode(
          map,
          { current: mapService.current!.getSelectInteraction() },
          mapService.current!.getMarkers(),
          mapService.current!.getLines(),
          mapService.current!.getPolygons(),
          onSelect,
          mode
        ),
        mapService.current!.getLastSelectMode()
      );
    }
  };

  const handleSelectClick = () => {
    const map = mapService.current?.getMap();
    if (selectMode && map) {
      enableSelectMode(
        map,
        { current: mapService.current!.getSelectInteraction() },
        mapService.current!.getMarkers(),
        mapService.current!.getLines(),
        mapService.current!.getPolygons(),
        undefined,
        selectMode
      );
    }
  };
  const handleExitSelect = () => {
    console.log('[DEBUG] handleExitSelect called');
    if (mapService.current) {
      const selectInteraction = mapService.current.getSelectInteraction();
      console.log('[DEBUG] selectInteraction in handleExitSelect:', selectInteraction);
      disableSelectMode({ current: selectInteraction });
    }
  };

  const handleSelectModeChange = (mode: 'single' | 'rectangle' | 'polygon') => {
    setSelectMode(mode);
    setSelectDropdown(false);
    const map = mapService.current?.getMap();
    if (map) {
      enableSelectMode(
        map,
        { current: mapService.current!.getSelectInteraction() },
        mapService.current!.getMarkers(),
        mapService.current!.getLines(),
        mapService.current!.getPolygons(),
        undefined,
        mode
      );
    }
  };

  return (
    <div style={{
      display: 'flex',
      gap: 16,
      background: 'rgba(255,255,255,0.0)',
      borderRadius: 12,
      boxShadow: 'none',
      padding: 0,
      alignItems: 'center',
      pointerEvents: 'auto',
      backdropFilter: 'none',
    }}>

      <div style={{ position: 'relative', display: 'inline-block' }}>
        {!isDrawing ? (
          <button
            style={{ ...buttonStyle }}
            onClick={() => setActiveDraw(activeDraw ? null : 'draw-menu')}
          >
            开始绘图
          </button>
        ) : (
          <button
            style={{ ...buttonStyle }}
            onClick={handleStopDraw}
          >
            停止绘制
          </button>
        )}
        {!isDrawing && activeDraw === 'draw-menu' && (
          <div style={{ position: 'absolute', top: '100%', left: 0, zIndex: 11, background: '#fff', border: '1px solid #ddd', borderRadius: 4, minWidth: 120, boxShadow: '0 2px 8px #0001' }}>
            <div style={{ padding: 8, cursor: 'pointer' }} onClick={() => { handleDrawClick('marker'); setActiveDraw(null); }}>添加标记</div>
            <div style={{ padding: 8, cursor: 'pointer' }} onClick={() => { handleDrawClick('polyline'); setActiveDraw(null); }}>绘制线</div>
            <div style={{ padding: 8, cursor: 'pointer' }} onClick={() => { handleDrawClick('polygon'); setActiveDraw(null); }}>绘制多边形</div>
          </div>
        )}
      </div>
      <div style={{ position: 'relative', display: 'inline-block' }}>
        <button
          style={{ ...buttonStyle, boxShadow: selectDropdown ? '0 0 0 2px #88855' : undefined }}
          onClick={() => setSelectDropdown(v => !v)}
        >
          选中要素
          <span style={{ marginLeft: 4 }}>▼</span>
        </button>
        {selectDropdown && (
          <div style={{ position: 'absolute', top: '100%', left: 0, zIndex: 10, background: '#fff', border: '1px solid #ddd', borderRadius: 4, minWidth: 120 }}>
            <div style={{ padding: 8, cursor: 'pointer', background: selectMode === 'single' ? '#eee' : undefined }} onClick={() => handleSelectModeChange('single')}>单击选中</div>
            <div style={{ padding: 8, cursor: 'pointer', background: selectMode === 'rectangle' ? '#eee' : undefined }} onClick={() => handleSelectModeChange('rectangle')}>矩形框选</div>
            <div style={{ padding: 8, cursor: 'pointer', background: selectMode === 'polygon' ? '#eee' : undefined }} onClick={() => handleSelectModeChange('polygon')}>多边形选中</div>
          </div>
        )}
      </div>
      {selectMode !== 'single' && (
        <button style={{ ...buttonStyle }} onClick={handleExitSelect}>退出选择</button>
      )}
      <button 
        style={{ ...buttonStyle }}
        onClick={() => {
          const map = mapService.current?.getMap();
          if (map) {
            // fitBounds 迁移到 drawing/mapDrawingActions
            import('../drawing/mapDrawingActions').then(({ fitBounds }) => {
              fitBounds(
                map,
                mapService.current!.getMarkers(),
                mapService.current!.getLines(),
                mapService.current!.getPolygons()
              );
            });
          }
        }}
      >
        缩放至全部
      </button>
      <button 
        style={{ ...buttonStyle }}
        onClick={() => mapService.current?.clearLayers()}
      >
        清除所有
      </button>
    </div>
  );
};
